<template>
  <div class="app-container">
    <div class="collect-gateway">
      <el-form v-column="3" :model="dataFilter">

        <el-form-item label="组织">
          <org-tree-select ref="orgSelect" v-model="dataFilter.orgId" @change="getList" />
        </el-form-item>

        <el-form-item label="网关名称/编号/型号">
          <el-input v-model="dataFilter.text" placeholder="请输入"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="handleDelete">删除</el-button>
      </div>
      <el-table
        :data="sourceData.list"
        border
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column label="网关名称" prop="gatewayName" />
        <el-table-column label="网关编号(SN)" prop="snCode" />
        <el-table-column label="网关型号" prop="gatewayType" />
        <el-table-column label="心跳周期" prop="heartCycle" />
        <el-table-column label="最后采集时间" prop="acqTime" width="180" />
        <el-table-column label="所属组织" prop="orgId" >
          <template #="{row}">
            {{ row.orgName }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
    </div>
  </div>

  <GatewayListDialog ref="dialog" @listChange="itemData" />
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { gatewayList, gatewayDetail, dellGateway } from '@/api/collect'
import Pagination from '@/components/Pagination/Index.vue'
import GatewayListDialog from './components/GatewayListDialog.vue'
import OrgTreeSelect from '@/components/OrgTreeSelect/index.vue'

const dataFilter = reactive({
  orgId: null,
  text: undefined,
})

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const sourceData = reactive({
  list: [] as any,
})

const getList = () => {
  gatewayList({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res)=>{
    console.log('res', res)
    sourceData.list = res.data.records
    // TODO use real api total res total
    pageProps.value.total = res.data.total
  })
  .catch((err) => {
    console.error('err', err)
  })
}

getList()

const onSearch = () => {
  getList()
}

const onReset = () => {
  // TODO use method component
  dataFilter.orgId = null
  dataFilter.text = undefined
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  })
}

const dialog: any = ref(null)

const handleAdd = () => {
  // dialog.value.reset()
  // console.log('tableItem', dialog.value.tableItem)
  dialog.value.dialogVisible = true
  dialog.value.isDisabled = true
  dialog.value.dialogStatus = 'create'
}

const handleView = (row: any) => {
  console.log('row', row)
  dialog.value.dialogVisible = true
  dialog.value.isDisabled = false
  dialog.value.dialogStatus = 'view'
  nextTick(()=>{
    gatewayDetail(row.id)
    .then((res)=>{
      console.log('res', res)
      Object.assign(dialog.value.formItem, res.data)
      // 确保 mqttProtocolName 字段正确转换为数字类型（0=盛为MQTT协议，1=正泰MQTT协议）
      if (res.data.mqttProtocolName !== null && res.data.mqttProtocolName !== undefined) {
        dialog.value.formItem.mqttProtocolName = Number(res.data.mqttProtocolName)
      }
    })
    .catch((err)=>{
      console.error('err', err)
    })
  })
}

const handleEdit = (row: any) => {
  dialog.value.dialogVisible = true
  dialog.value.dialogStatus = 'edit'
  nextTick(()=>{
    gatewayDetail(row.id)
    .then((res)=>{
      console.log('res', res)
      dialog.value.isDisabled = true
      Object.assign(dialog.value.formItem, res.data)
      // 确保 mqttProtocolName 字段正确转换为数字类型（0=盛为MQTT协议，1=正泰MQTT协议）
      if (res.data.mqttProtocolName !== null && res.data.mqttProtocolName !== undefined) {
        dialog.value.formItem.mqttProtocolName = Number(res.data.mqttProtocolName)
      }
    })
    .catch((err)=>{
      console.error('err', err)
    })
  })
}

const itemData = () => {
  getList()
}

const multipleSelection = ref<any>([])

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val.map(item=>item.id);
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {  
    const params = {
      idList: multipleSelection.value
    }
    if (row.id) params.idList = [row.id]
    dellGateway(params)
    .then((res: any) => {
      ElMessage.success('删除成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.success('删除失败！')
      getList()
    })
  })
  .catch(() => {})
}
</script>

<style scoped>
.app-container {
  flex: 1;
}
</style>